package com.qf.application.web.filter;

import com.alibaba.fastjson.JSON;
import com.qf.application.entity.User;
import com.qf.application.utils.result.Result;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

@WebFilter(filterName = "LoginFilter",urlPatterns = "/*")
public class LoginFilter implements Filter {

    @Resource(name = "JsonRedisTemplate")
    private RedisTemplate redisTemplate;

    private String loginKey = "loan:login:%s";

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String servletPath = request.getServletPath();
        System.out.println("用户请求的路径：" + servletPath);

        if("/user/login".equals(servletPath)){
            filterChain.doFilter(request, response);
            return;
        }
        //if("/ws/myws".equals(servletPath)){
        //    filterChain.doFilter(request, response);
        //    return;
        //}
        //
        //if("OPTIONS".equals(request.getMethod())){
        //    filterChain.doFilter(request, response);
        //    return;
        //}

        String gToken = request.getHeader("g_token");
        System.out.println("gToken = " + gToken);
        Result result = null;
        if(!StringUtils.isEmpty(gToken)){
            String format = String.format(loginKey, gToken);
            Object o = redisTemplate.opsForValue().get(format);
            if (o == null) {
                result = Result.error(502,"token 已经过时，请重新登录");
            }
            try {
                 format = String.format(loginKey, gToken);
                 o = redisTemplate.opsForValue().get(format);
                if(StringUtils.isEmpty(o)){
                    result = Result.error(502,"token 已经过时，请重新登录");
                }
                System.out.println("o = " + o);
                // 放行
                filterChain.doFilter(request,response);
                return;

            } catch (Exception ex){
                result = Result.error(501,"请先登录");
            }

        //}else{
        //    // 2.3 如果有token 解析token
        //    try {
        //        String format = String.format(loginKey, gToken);
        //        Object o = redisTemplate.opsForValue().get(format);
        //        if(StringUtils.isEmpty(o)){
        //            result = Result.error(502,"token 已经过时，请重新登录");
        //            return;
        //        }
        //        System.out.println("o = " + o);
        //        // 放行
        //
        //    } catch (Exception ex){
        //        result = Result.error(501,"请先登录");
        //    }
        }

        response.setCharacterEncoding("utf-8");
        response.setContentType("text/json");

        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with, Content-Type");
        response.setHeader("Access-Control-Allow-Credentials", "true");  // 1

        response.getWriter().write(JSON.toJSONString(result));


    }
}
